package com.example.friend.component.manager;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.core.constants.CacheConstants;
import com.example.friend.entity.DO.UserDO;
import com.example.friend.entity.VO.UserDetailVO;
import com.example.friend.mapper.UserMapper;
import com.example.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;

    public UserDetailVO getUserById(Long userId) {
        String userKey = getUserKey(userId);
        UserDetailVO userVO = redisService.getCacheObject(userKey, UserDetailVO.class);
        if (userVO != null) {
            //将缓存延长10min
            redisService.expire(userKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
            return userVO;
        }
        LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserDO::getUserId, userId);
        UserDO user = userMapper.selectOne(wrapper);
        if (user == null) {
            return null;
        }
        refreshUser(user);
        userVO = new UserDetailVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    public void refreshUser(UserDO user) {
        //刷新用户缓存
        String userKey = getUserKey(user.getUserId());
        redisService.setCacheObject(userKey, user);
        //设置用户缓存有效期为10分钟
        redisService.expire(userKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }

    //u:d:用户id
    private String getUserKey(Long userId) {
        return CacheConstants.USER_DETAIL + userId;
    }
}
